package com.cxl.price.action.price;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import com.cxl.parser.grab.GrabCommon;
import com.cxl.price.bean.Brand;
import com.cxl.price.bean.Good;
import com.cxl.price.bean.ItemCat;
import com.cxl.price.bean.Model;
import com.cxl.price.bean.Ptype;
import com.cxl.price.bean.Shop;
import com.cxl.price.bean.TaoBaoGood;
import com.cxl.price.service.BrandService;
import com.cxl.price.service.GoodsService;
import com.cxl.price.service.ItemCatService;
import com.cxl.price.service.ModelService;
import com.cxl.price.service.PtypeService;
import com.cxl.price.service.ShopService;
import com.cxl.price.service.TaoBaoGoodService;
import com.cxl.price.top.service.TaoBaoApiService;
import com.cxl.price.top.service.TopItemResponseService;
import com.cxl.price.top.service.TopProductService;
import com.cxl.price.top.service.TopShopService;
import com.cxl.price.util.JsonBinder;
import com.cxl.price.util.RegexpGood;
import com.summer.core.action.BaseAction;
import com.summer.core.bean.Pager;
import com.taobao.api.ApiException;
import com.taobao.api.domain.Product;
import com.taobao.api.domain.SellerCat;
import com.taobao.api.request.ProductGetRequest;
import com.taobao.api.request.SellercatsListGetRequest;
import com.taobao.api.response.ProductGetResponse;

/**
 * @about: 产品类型 action
 * @author: wwwlike
 * @create: 2011-06-23
 */
 
 
@ParentPackage("price")			
public class PtypeAction extends BaseAction<Ptype, PtypeService> {

	List<Shop> shopList=null;
	
	
	public List<Shop> getShopList() {
		return shopList;
	}

	//淘宝商品service
	private TaoBaoGoodService taoBaoService;
	//淘宝目录
	private ItemCatService itemCatService;
	//淘宝品牌
	public BrandService brandService;
	//淘宝型号
	public ModelService modelService;
	
	public GoodsService goodsService;
	
	public ShopService shopService;
	
	
	
	@Resource
	public void setShopService(ShopService shopService) {
		this.shopService = shopService;
	}

	@Resource
	public void setGoodsService(GoodsService goodsService) {
		this.goodsService = goodsService;
	}

	@Resource
	public void setModelService(ModelService modelService) {
		this.modelService = modelService;
	}

	@Resource
	public void setBrandService(BrandService brandService) {
		this.brandService = brandService;
	}
	
	@Resource
	public void setItemCatService(ItemCatService itemCatService) {
		this.itemCatService = itemCatService;
	}

	public void setPtype(Ptype ptype) {
		setBean(ptype);
	}

	public Ptype getPtype() {
		return getBean();
	}

	public String shopid;
	
	public String getShopid() {
		return shopid;
	}

	public void setShopid(String shopid) {
		this.shopid = shopid;
	}
	
	
	
	@Resource
	public void setTaoBaoService(TaoBaoGoodService taoBaoService) {
		this.taoBaoService = taoBaoService;
	}

	@Resource
	public void setService(PtypeService service) {
		this.service = service;
	}
	
	
	public String list() throws Exception
	{
        if(shopid.contains(","))
        {
        	shopid=shopid.split(",")[0];
        }
        
       TopShopService shop=new TopShopService();
       List<SellerCat> SellerCatList= topBaseService.getTaobaoResponse(SellercatsListGetRequest.class,getRequest()).getSellerCats();
       getRequest().setAttribute("catList", SellerCatList);
       
       TopItemResponseService topItem=new TopItemResponseService();
       
//       	List<Postage> postageList= topItem.get.getPostagesGetResponse().getPostages();
//      
//        getRequest().setAttribute("postageList", postageList);
        
       
//		if(pager==null)
			pager=new Pager();
//		pager.setProperty("shop.id");
//		pager.setKeyword(shopid);
			
		pager.setList(service.getList("shop.id", shopid));
		shopList=shopService.getAll();
		
		
		return result(LIST);
	}

	/**
	 * 导入单个京东
	 * @return
	 * @throws ApiException
	 */
	public String importTaoBaoGood() throws ApiException
	{
		
		
		
		  if(shopid.contains(","))
	        {
	        	shopid=shopid.split(",")[0];
	        }
		  Shop shop=shopService.get(shopid);
		  String shopCategoryId=getRequest().getParameter("shopCategoryId");
		  
		try
		{
		TaoBaoApiService taobaoApiSer=new TaoBaoApiService();
		String itemcatName=getRequest().getParameter("itemCat.name");
		ItemCat cat=null;
		if(itemcatName!=null&&!"".equals(itemcatName))
		{
		String itemCatId=itemcatName.split("\\|")[1];
		cat=itemCatService.get(itemCatId);
		}
		String urltemp=getRequest().getParameter("goodUrl");
		
		Long cid=null;
		if(cat!=null)
			cid=cat.getCid();
		
		//下属没有品牌就加入
		if(cat!=null&&brandService.getList("itemCat.cid", cid).size()==0)
		{
			List<Brand> list=taobaoApiSer.getBrands(cat.getCid());
			for(Brand brand :list)
			{
				brand.setItemCat(cat);
				brandService.save(brand);
			}
		}
		
		GrabCommon grab=(GrabCommon)Class.forName(shop.getGrabClassPath()).newInstance();
		grab.setUrl(urltemp);
		importOne(urltemp, cat, taobaoApiSer, 1000,grab,shopCategoryId);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		return result(LIST);
	}
	
	
	/**
	 * @author dlc ajax搜索
	 * @return
	 * @throws Exception
	 */
	public String searchByKey() throws Exception{
		Shop shop=shopService.get(shopid);
		String url=shop.getSearchKey()+java.net.URLEncoder.encode(getParameter("searchKey"),"utf-8");
		GrabCommon grab=(GrabCommon)Class.forName(shop.getGrabClassPath()).newInstance();
		grab.setUrl(url);//设置搜索的URL
		List<Good> list=grab.getAllNextGoodsUrl();
		JsonBinder gson = new JsonBinder();
		return ajaxJson(gson.toJson(list));
	}
	
	/**
	 * 导入单个类目
	 * @return
	 * @throws ApiException
	 */
	public String importTaoBaoGoods() throws ApiException
	{
		try
		{
			
			  if(shopid.contains(","))
		        {
		        	shopid=shopid.split(",")[0];
		        }
			  Shop shop=shopService.get(shopid);
			  
			  
		//导入淘宝类目	
//			if(itemCatService.getAll().size()==0)
//			{
//				itemCatService.addItemCats();
//				return null;
//			}
			
			
	
//			
			String shopCategoryId=getRequest().getParameter("shopCategoryId");
			
		
			
			
			
			double price=500;
			if(StringUtils.isNotEmpty(getRequest().getParameter("price")))
				price=Double.parseDouble(getRequest().getParameter("price"));
			int num=20;
			if(StringUtils.isNotEmpty(getRequest().getParameter("num")))
				num=Integer.parseInt(getRequest().getParameter("num"));
			
			String itemcatName=getRequest().getParameter("itemCat.name");
			ItemCat cat=null;
			if(StringUtils.isNotEmpty(itemcatName))
			{
			String itemCatId=itemcatName.split("\\|")[1];
			cat=itemCatService.get(itemCatId);
			}
	
		TaoBaoApiService taobaoApiSer=new TaoBaoApiService();
	
		/**
		 * url 如果搜索url有就表示本导入是导入搜索页面的
		 *     否则就是导入制定类目url的
		 */
			String url=getRequest().getParameter("goodsUrl");
		
			if(StringUtils.isEmpty(url))
			 url=service.get(ids[0]).getUrl();
			else if(url.indexOf("http")!=-1) //搜索地址里面放的是http就不按照下面进行汉字搜索
			 url=getRequest().getParameter("goodsUrl");
			else 
				url=shop.getSearchKey()+java.net.URLEncoder.encode(getRequest().getParameter("goodsUrl"),shop.getEncode());
			
			
			Long cid=null;
			if(cat!=null)
			{
				cid=cat.getCid();
			}
			
			//下属没有品牌就加入 且 类目不为空
			if(cat!=null&&brandService.getList("itemCat.cid", cid).size()==0)
			{
				List<Brand> list=taobaoApiSer.getBrands(cat.getCid());
				for(Brand brand :list)
				{
					brand.setItemCat(cat);
					brandService.save(brand);
				}
			}
			GrabCommon grab=(GrabCommon)Class.forName(shop.getGrabClassPath()).newInstance();
			grab.setUrl(url);
		
			grab.setSearchMaxNum(num);
			List<Good> urllist=grab.getAllNextGoodsUrl();
			//搜索指定数目的
			if(urllist.size()>num)
			{
				urllist=urllist.subList(0, num);
			}
			for(Good urltemp:urllist)
			{
				String ajaxurl="http://127.0.0.1:10000/?delay=1000&url="+urltemp.getUrl();
				grab.setUrl(urltemp.getUrl());
				importOne(urltemp.getUrl(), cat, taobaoApiSer, price,grab,shopCategoryId);
			}
		
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		return result(LIST);
	}
	
	
	/**
	 * 导入一个商品 供Action效用
	 * @param urltemp
	 * @param cat
	 * @param taobaoApiSer
	 * @param grab
	 * @param price
	 */
	public void importOne(String urltemp,ItemCat cat,TaoBaoApiService taobaoApiSer,double price,GrabCommon grab,String shopCategoryId)
	{
			try
			{
				//运费模板  0 卖家承担  其他的 是买家承担
				String postId=getRequest().getParameter("postId");
				
				String vedios=getRequest().getParameter("vedios");
				
			double thisPrice=grab.getPrice();
			String brand="松下";//grab.getBrand();
			
			String xingHao="XQB65-Q76201";//grab.getXingHao();
			String title ="松下 XQB65-Q76201";//grab.getTitle();
			if(xingHao!=null&& brand!=null)
			xingHao=xingHao.substring(xingHao.indexOf(brand)+brand.length());
			Pager page=new Pager();
			page.setKeyword(brand+"%"+xingHao);
			page.setProperty("name");
			//小于设定的价格就继续  && 判断品牌 型号 在goods里 有没有 有就不进去了
			if(thisPrice<=price&&goodsService.findByPager(page).getList().size()==0)
			{
				TaoBaoGood good=taoBaoService.getObjFromUrl(urltemp);
				String pic=grab.getImgHref();
			
			//查询匹配的品牌
			Brand brandObj=null;
			if(cat!=null)
				brandObj=brandService.getBrandByCidAndName(cat.getCid(), title);
			//品牌不为空
			if(brandObj!=null)
			{
				Long brandVid=brandObj.getVid();
				good.setPopvalue("20000:"+brandVid+";");
				
				
				//进行型号查找。没有该品牌型号 先加入型号
				if(brandObj.getModels()==null||brandObj.getModels().size()==0)
				{ 
					String pid_vid=brandObj.getPid()+":"+brandObj.getVid();
					List<Model> list=taobaoApiSer.getModels(cat.getCid(), pid_vid);
					if(list!=null)
					{
					for(Model model :list)
					{
						model.setBrand(brandObj);
						modelService.save(model);
					}
					}
					
				}
				List<Model> modellist=modelService.getList("brand.id", brandObj.getId());
				
				Iterator<Model> it=modellist.iterator();
				
				RegexpGood	regexp=null;
				while(it.hasNext())
				{
					Model md=it.next();
					
					regexp=new RegexpGood(null,md.getName(), title);
					if(regexp.comp())
					{
						good.setPopvalue(good.getPopvalue()+md.getPid()+":"+md.getVid()+";");
						break;
					}
					
//					if(md.getName().toLowerCase().contains(xingHao.toLowerCase()))
//					{
//						good.setPopvalue(good.getPopvalue()+md.getPid()+":"+md.getVid()+";");
//						break;
//					}
				}
			}
			
			//保存附属图片
			List<String> imgS=grab.getOtherImgsHref();
			for(int i=1;i<imgS.size();i++)
			{
				pic=pic+";"+imgS.get(i);
			}
			good.setPic(pic);
		
			String content=grab.getContent();
			good.setDescription(content);
			good.setFromUrl(urltemp);
			good.setPostId(postId);
			good.setVedios(vedios);
			good.setShopCategoryId(","+shopCategoryId+",");
			
			
				good.setPrice(thisPrice+"");
				good.setCategory((cat!=null?cat.getCid():"")+"");
				/*
				 * 
				 * [^\/:*? " <> !]+
		String reg ="[\n-\r]";
		   Pattern p = Pattern.compile(reg);
		   Matcher m = p.matcher(reStr);
		   reStr = m.replaceAll("");
		
		   reg ="[\t]";
		   p = Pattern.compile(reg);
		  m = p.matcher(reStr);
		  reStr = m.replaceAll("");
				 * 
				 * */
				String title1="";
				if(brand==null||xingHao==null)
				{
					title1=title;
				}
				else
				{
				 title1="["+brand+" "+xingHao+"]"+title.replace(brand, "").replace(xingHao,"")+" 联保 发票";
				String picName=(brand+" "+xingHao).replace("\\\\"," ").replace("/"," ");
				good.setNewPic(picName);
				}
				String pciTbiStr=RandomStringUtils.random(20,true,true);
				good.setPic_status(pciTbiStr);
			
				//有品牌 有型号 去匹配非关键属性
				if(good.getPopvalue()!=null&&good.getPopvalue().split(";").length==2)
				{
					TopProductService productServcie=new TopProductService();
					ProductGetRequest ee=new ProductGetRequest();
					ee.setCid(Long.parseLong(good.getCategory()));
					ee.setFields("product_id,cid,cat_name,props,props_str,name,binds,binds_str,sale_props,sale_props_str,price,desc,pic_url,created,modified,product_img.id,product_img.url,product_img.position,product_prop_img.id,product_prop_img.props,product_prop_img.url,product_prop_img.position");
					ee.setProps(good.getPopvalue());
					ProductGetResponse re=productServcie.getProductGetResponse(ee);
					Product product=re.getProduct();
					
					if(product!=null)
					{
						good.setPopvalue(good.getPopvalue()+product.getBinds());
						title1="["+product.getName()+"]"+title.replaceAll(brand+"", "").replaceAll(xingHao+"","");
					}
				}
		
				good.setTitle(title1);
				taoBaoService.addTaoBaoGood(good);
				
				
				
//				ImageUtil image=new ImageUtil();
//				//image.saveToFile(pic,picName);
//				if(!"0".equals(vedios)&&!"-1".equals(vedios))
//				{
//					//指定水印
//				 image.pressImage(vedios+".png", picName+".jpg", 1, 0.8f);
//				}
//				else if("-1".equals(vedios))
//				{
//					int num = new Random().nextInt(3);
//					image.pressImage(num+".png", picName+".jpg", 1, 0.8f);
//				}
//				image.addBorderToImage(picName+".jpg");
				
				
				
				
				
				
				
				// image.saveToTbi(pic,pciTbiStr);
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
/**
 * 
			
//			{
			List<ItemCat> listCats= itemCatService.findByPager(pager).getList();//现在这个不是模糊查询 稍后要改，且可能查询多个  但是一定要是叶子节点
		
			
			int minlength=0;
			for(ItemCat cattemp:listCats)
			{
				if(cattemp.getIs_parent()==false&&(minlength==0||minlength>cattemp.getName().length()))
				{
					minlength=cattemp.getName().length();
					cat=cattemp;
				}
			 }
 * @throws UnsupportedEncodingException 
			 
			 
 */
	  public static void main(String[] args) throws Exception {
		  String pciTbiStr=RandomStringUtils.random(20,true, true);
		  System.out.println(pciTbiStr);
		  
			String url="http://search.jd.com/Search?enc=utf-8&keyword="+java.net.URLEncoder.encode("洗衣机","utf-8");
			GrabCommon grab=(GrabCommon)Class.forName("com.cxl.parser.grab.Grab360buy").newInstance();
			grab.setUrl(url);
			grab.setSearchMaxNum(90);
			List<Good> list=grab.getAllNextGoodsUrl();
			for(Good good:list){
				System.out.println(good.getSku());
				System.out.println(good.getTitle());
				System.out.println(good.getPic_url());
			}
			
			System.out.println(url);
 }

	

}
